﻿using BarcodeLib;
using Business;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PFTPickTaskPrint
{
    public partial class Form1 : Form
    {
        static string outStockScanTime = ConfigurationManager.AppSettings["ScanoutStockTime"];//摘果补货定时器时间间隔
        System.Timers.Timer outStockScanTimer;//摘果补货定时器
        private PrintDialog printDialog1 = new PrintDialog();
        private int GoodsidForDetail = -1;
        private PrintPreviewDialog PrintPreview = new PrintPreviewDialog();//打印预览
        private PrintDocument printDocumentForOutStock = new PrintDocument();//补货打印文档
        private PrintDocument printDocumentForPftBatch = new PrintDocument();//分拣打印文档
        private PrintDocument printDocumentForOffShelves = new PrintDocument();//下架打印文档
        private PrintDocument printDocumentForDetail = new PrintDocument();//配方打印文档
        private PrintDocument printDocumentForWOC = new PrintDocument();//配方打印文档预览
        private PrintDocument printDocumentForBatch = new PrintDocument();//二楼批次打印文档
        private int pagenow = 0; //补货打印页数
        private int papercount = 1; //补货打印总页数
        private int pageBatchnow = 0; //批次/下架 打印页数
        private int paperBatchcount = 1; //批次/下架 打印总页数
        private List<GoodsInfo> list = new List<GoodsInfo>();
        private List<PrintBatchModel> Batchlist = new List<PrintBatchModel>();
        private List<PrintOffShelvesModel> Offlist = new List<PrintOffShelvesModel>();
        private List<MachingDetailModel> listForPrint = new List<MachingDetailModel>();
        private List<MachingDetailModel> listBatchNo = new List<MachingDetailModel>();
        private List<MachingDetailModel> listM = new List<MachingDetailModel>();
        bool _isLight;
        bool isLight
        {
            get { return _isLight; }
            set { _isLight = value; }
        }
        public Form1()
        {
            InitializeComponent();
            InitprinterComboBox();
            RYB_PTL_API.RYB_PTL.UserResultAvailable += new RYB_PTL_API.RYB_PTL.UserResultAvailableEventHandler(RYB_PTL_UserResultAvailable);
            printDocumentForOutStock.PrintPage += new PrintPageEventHandler(printDocumentForOutStock_PrintPage);
            printDocumentForPftBatch.PrintPage += new PrintPageEventHandler(printDocumentForPftBatch_PrintPage);
            printDocumentForOffShelves.PrintPage += new PrintPageEventHandler(printDocumentForOffShelves_PrintPage);
            printDocumentForWOC.PrintPage += new PrintPageEventHandler(printDocumentForWOC_PrintPage);
            printDocumentForDetail.PrintPage += new PrintPageEventHandler(printDocumentForDetail_PrintPage);
            printDocumentForBatch.PrintPage += new PrintPageEventHandler(printDocumentForBatch_PrintPage);
        }

        public class LocalPrinter
        {
            private static PrintDocument fPrintDocument = new PrintDocument();
            ///
            /// 获取本机默认打印机名称
            ///
            public static String DefaultPrinter
            {
                get { return fPrintDocument.PrinterSettings.PrinterName; }
            }
            ///
            /// 获取本机的打印机列表。列表中的第一项就是默认打印机。
            ///
            public static List<string> GetLocalPrinters()
            {
                List<string> fPrinters = new List<string>();
                fPrinters.Add(DefaultPrinter); // 默认打印机始终出现在列表的第一项
                foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
                {
                    if (!fPrinters.Contains(fPrinterName))
                        fPrinters.Add(fPrinterName);
                }
                return fPrinters;
            }
        }
        public class Externs
        {
            [DllImport("winspool.drv")]
            public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
        }

        private T GetNewObject<T>(T info)
        {
            try
            {
                var s = JsonConvert.SerializeObject(info);
                T infotmp1 = JsonConvert.DeserializeObject<T>(s);
                return infotmp1;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        //窗体关闭前处理事件
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);//退出窗体线程及电子标签拖管线程
        }
        private void InitprinterComboBox()
        {
            List<String> list = LocalPrinter.GetLocalPrinters(); //获得系统中的打印机列表
            foreach (String s in list)
            {
                printerComboBox.Items.Add(s); //将打印机名称添加到下拉框中
            }
        }

        //设置默认打印机
        private void printButton_Click_1(object sender, EventArgs e)
        {
            if (printerComboBox.SelectedItem != null) //判断是否有选中值
            {
                if (Externs.SetDefaultPrinter(printerComboBox.SelectedItem.ToString())) //设置默认打印机
                {
                    MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机成功！");
                }
                else
                {
                    MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机失败！");
                }
            }
        }

        #region 多线程打印委托
        private delegate void PrintDocumentEve();
        private void PrintElecLabel()//补货
        {
            this.printDocumentForOutStock.Print();
        }
        private void PrintBatchLabel()
        {
            this.printDocumentForPftBatch.Print();
        }
        private void PrintOffShelvesLabel()
        {
            this.printDocumentForOffShelves.Print();
        }
        private void PrintDoc(PrintDocumentEve print)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(print);
            }
            else
            {
                print();
            }
        }
        #endregion

        #region 事件触发返回值
        /// <summary>
        /// 说明：只要标签有返回值都会自动触发事件绑定的此函数
        /// </summary>
        /// <param name="rs"></param>
        private void RYB_PTL_UserResultAvailable(RYB_PTL_API.RYB_PTL.RtnValueStruct rs)
        {
            try
            {
                string sIp = rs.Ip;
                string sTagId = rs.Tagid.ToString();//扫描枪ID
                string errorMag = "";
                string ProduceBatch = "";//扫描枪返回值
                string spacemark = "FF";//亮灯显示间隔符

                DisplayRichTextBox("rs.Ip:" + rs.Ip + " rs.Tagid:" + rs.Tagid + " rs.Number:" + rs.Number + " rs.KeyCode:" + rs.KeyCode + " rs.Locator:" + rs.Locator);
                if (sTagId.StartsWith("FC"))//确定是否扫码枪 
                {
                    ProduceBatch = rs.Number;
                    List<ProduceLightLabel> list = new ProduceGoods().getLightElecLabel(ProduceBatch, sTagId);
                    if ((list != null) && (list.Count > 0))
                    {
                        foreach (ProduceLightLabel item in list)
                        {
                            if ((item.FINISHQTY != 0) || (string.IsNullOrEmpty(item.FINISHQTY.ToString())))//已拍灯
                            {
                                if (item.FINISHQTY == item.QTY)//是否有缺货数
                                {
                                    continue; //跳过本次循环
                                }
                                else
                                {
                                    _isLight = RYB_PTL_API.RYB_PTL.RYB_PTL_DspDigit8Spec(item.IPADDRESS.Trim(), item.LABELID.PadLeft(4, '0'), Convert.ToInt32(item.BOMQTY).ToString(), spacemark, Convert.ToInt32((item.QTY - item.FINISHQTY)), 1, 1, 3);
                                    DisplayRichTextBox(string.Format("亮灯Ip地址:{0},标签ID：{1},数量:{2},亮灯结果:{3}", item.IPADDRESS.Trim(), sTagId, item.LABELID.PadLeft(4, '0'), item.QTY, _isLight));
                                    continue;
                                }
                            }
                            _isLight = RYB_PTL_API.RYB_PTL.RYB_PTL_DspDigit8Spec(item.IPADDRESS.Trim(), item.LABELID.PadLeft(4, '0'), Convert.ToInt32(item.BOMQTY).ToString(), spacemark, Convert.ToInt32(item.QTY), 1, 1, 3);
                            string sCombineStrToRichTextBox = string.Format("亮灯Ip地址:{0},标签ID：{1},数量:{2},亮灯结果:{3}", item.IPADDRESS.Trim(), sTagId, item.LABELID.PadLeft(4, '0'), item.QTY, _isLight);
                            DisplayRichTextBox(sCombineStrToRichTextBox);
                        }
                        if (_isLight)
                        {
                            new ProduceGoods().updateLightElecLable(ProduceBatch, sTagId, out errorMag);//更新明细为亮灯状态
                            DisplayRichTextBox(string.Format("Ip地址:{0},标签ID：{1},批次:{2},处理结果:{3}", list[0].IPADDRESS.Trim(), sTagId, list[0].PRODUCEBATCH, errorMag));
                        }
                    }
                    else
                    {
                        errorMag = "无数据";
                        DisplayRichTextBox("亮灯失败！原因：" + errorMag);
                    }
                    return;
                }
                string sKeyCode = rs.KeyCode;
                string sLocator = rs.Locator;
                int sValue = int.Parse(rs.Number);
                if (!string.IsNullOrEmpty(sIp))
                {
                    if (new ProduceGoods().PressElecLabelReaction(sIp, sTagId, sValue, out errorMag))//拍灯数据写入
                    {
                        string sCombineStrToRichTextBox = string.Format("Ip地址:{0},标签ID：{1},货位:{2},特征值:{3},返回数值:{4}", sIp, sTagId, sLocator, sKeyCode, sValue);
                        DisplayRichTextBox(sCombineStrToRichTextBox);
                        isLight = false;
                    }
                    else
                    {
                        DisplayRichTextBox("写入数据失败！原因：" + errorMag);
                    }
                }
                else
                {
                    isLight = true;
                }
            }
            catch (Exception ex)
            {
                DisplayRichTextBox("标签扫描枪监测事件处理异常:" + ex.Message);
            }
        }

        /// <summary>
        /// 说明：显示返回值结果
        /// </summary>
        /// <param name="s"></param>
        private delegate void DelegateDisplay(string s);
        private void DisplayRichTextBox(string s)
        {
            if (InvokeRequired)
            {
                this.Invoke(new DelegateDisplay(DisplayRichTextBox), new object[] { s });
                return;
            }
            else
            {
                richTextBox.AppendText(string.Format("{0}  {1}\r\n", System.DateTime.Now.ToString(), s));
                richTextBox.ScrollToCaret();
                if (richTextBox.Lines.Count() > 1000)
                    richTextBox.Clear();
            }
        }
        #endregion

        #region 打印事件
        
        private void printDocumentForOutStock_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pagenow < papercount)//第一页打印的图片
            {
                try
                {
                    var info = list[pagenow];
                    DisplayRichTextBox(info.GOODSCODE + info.GOODSNAME);
                    new BGoods().UpdatePFTInventoryPrintDate(info.GOODSID);//更新打印日期
                    CreateOutStockImage(info.GOODSCODE, info.ROADWAY, info.INVQTY, info.GOODSNAME, info.AREA, info.TIER.ToString(), info.COLUMNS.ToString(), info.LOCATIONCODE);
                    Bitmap _NewBitmap = new Bitmap(groupBox_OutStock.Width, groupBox_OutStock.Height);
                    groupBox_OutStock.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                    e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
                    if (papercount - pagenow == 1)
                        e.HasMorePages = false;
                    else
                        e.HasMorePages = true;
                    pagenow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        private void printDocumentForPftBatch_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pageBatchnow < paperBatchcount)//第一页打印的图片
            {
                try
                {
                    var info = Batchlist[pageBatchnow];
                    DisplayRichTextBox("批次号：" + info.BATCHNO + " 位置：" + info.POSITION);
                    CreatePFTBatchImage(info.BATCHNO, info.APPORDERNO, info.POSITION);
                    Bitmap _NewBitmap = new Bitmap(groupBox_PftBatch.Width, groupBox_PftBatch.Height);
                    groupBox_PftBatch.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                    e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
                    if (paperBatchcount - pageBatchnow == 1)
                        e.HasMorePages = false;
                    else
                        e.HasMorePages = true;
                    pageBatchnow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        private void printDocumentForOffShelves_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pageBatchnow < paperBatchcount)//第一页打印的图片
            {
                try
                {
                    var info = Offlist[pageBatchnow];
                    DisplayRichTextBox(info.GOODSCODE + info.GOODSNAME + info.LOCATIONCODE);
                    CreateOffImage(info.GOODSCODE, info.GOODSNAME, info.LOCATIONCODE, info.ROADWAY, info.AREA, info.TIER, info.COLUMNS);
                    Bitmap _NewBitmap = new Bitmap(groupBox_OffShelves.Width, groupBox_OffShelves.Height);
                    groupBox_OffShelves.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                    e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
                    if (paperBatchcount - pageBatchnow == 1)
                        e.HasMorePages = false;
                    else
                        e.HasMorePages = true;
                    pageBatchnow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        private void printDocumentForWOC_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pagenow < papercount)//第一页打印的图片
            {
                try
                {
                    Bitmap _NewBitmap = new Bitmap(groupBox_ProduceGoods.Width, groupBox_ProduceGoods.Height);
                    groupBox_ProduceGoods.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                    e.Graphics.DrawImage(_NewBitmap, 0, 70, _NewBitmap.Width, _NewBitmap.Height);
                    if (papercount - pagenow == 1)
                    {
                        e.HasMorePages = false;
                    }
                    else
                    {
                        e.HasMorePages = true;
                    }
                    pagenow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                    DisplayRichTextBox("净菜详细打印异常:" + ex.Message);
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        private void printDocumentForDetail_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pagenow < papercount)//第一页打印的图片
            {
                try
                {
                    var info = listM[pagenow];
                    DisplayRichTextBox("批次号：" + info.PRODUCEBATCH + "商品名：" + info.GOODSNAME + "SEQ:" + info.SEQ);
                    if (info.SEQ == -2)
                    {
                        CreateCountImage(info.GOODSNAME, info.ALLQTY.ToString(), "");
                        Bitmap _NewBitmapNum = new Bitmap(groupBox_ProduceCount.Width, groupBox_ProduceCount.Height);
                        groupBox_ProduceCount.DrawToBitmap(_NewBitmapNum, new Rectangle(0, 0, _NewBitmapNum.Width, _NewBitmapNum.Height));
                        e.Graphics.DrawImage(_NewBitmapNum, 0, 70, _NewBitmapNum.Width, _NewBitmapNum.Height);
                    }
                    else if (info.SEQ == -1)
                    {
                        CreateCountImage(info.GOODSNAME, info.QTY.ToString(), info.PRODUCEBATCH);
                        Bitmap _NewBitmapNum = new Bitmap(groupBox_ProduceCount.Width, groupBox_ProduceCount.Height);
                        groupBox_ProduceCount.DrawToBitmap(_NewBitmapNum, new Rectangle(0, 0, _NewBitmapNum.Width, _NewBitmapNum.Height));
                        e.Graphics.DrawImage(_NewBitmapNum, 0, 70, _NewBitmapNum.Width, _NewBitmapNum.Height);
                    }
                    else
                    {
                        string single_manufactureDate = DateCheckbox.Checked == true ? single_manufactureDate = DateTime.Now.AddDays(1).ToShortDateString() : single_manufactureDate = DateTime.Now.ToShortDateString();
                        string single_FreshEndDate= DateCheckbox.Checked == true ? single_FreshEndDate = DateTime.Now.AddDays(3).ToShortDateString() : single_FreshEndDate = DateTime.Now.AddDays(2).ToShortDateString();
                        CreateProduceImage(info.GOODSCODE, info.GOODSNAME, info.BATCHING, single_manufactureDate, single_FreshEndDate, info.WEIGHT, info.STORAGE, info.COOKINGONE, info.COOKINGTWO, info.COOKINGTHREE, info.APPBATCH + "-" + info.ALLQTY + "-" + info.SEQ);
                        Bitmap _NewBitmap = new Bitmap(groupBox_ProduceGoods.Width, groupBox_ProduceGoods.Height);
                        groupBox_ProduceGoods.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                        e.Graphics.DrawImage(_NewBitmap, 0, 70, _NewBitmap.Width, _NewBitmap.Height);
                    }
                    if (papercount - pagenow == 1)
                    {
                        e.HasMorePages = false;
                    }
                    else
                    {
                        e.HasMorePages = true;
                    }
                    pagenow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                    DisplayRichTextBox("净菜详细打印异常:" + ex.Message);
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        private void printDocumentForBatch_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (pageBatchnow < paperBatchcount)//第一页打印的图片
            {
                try
                {
                    var info = listBatchNo[pageBatchnow];
                    DisplayRichTextBox("批次号：" + info.PRODUCEBATCH);
                    CreateBatchImage(info.PRODUCEBATCH, info.GOODSNAME, info.QTY);
                    Bitmap _NewBitmap = new Bitmap(groupBox_ProduceBatch.Width, groupBox_ProduceBatch.Height);
                    groupBox_ProduceBatch.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
                    e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
                    if (paperBatchcount - pageBatchnow == 1)
                    {
                        e.HasMorePages = false;
                    }
                    else
                    {
                        e.HasMorePages = true;
                    }
                    pageBatchnow++;
                }
                catch (Exception ex)
                {
                    e.HasMorePages = false;
                    DisplayRichTextBox("批次条码打印异常:" + ex.Message);
                }
            }
            else
            {
                e.HasMorePages = false;
            }
        }

        #endregion

        #region 打印创建图片
        //补货条码创建
        private void CreateOutStockImage(string Code, string roadway, int qty, string goodsName, string Area, string Tier, string Column, string Locationcode)
        {

            this.labGoodsCode.Text = roadway;
            this.labNumber.Text = qty.ToString();
            this.labGoodsName.Text = goodsName;
            this.labelPosition.Text = Area + "-" + Tier + "-" + Column;
            this.labelLocationcode.Text = Locationcode;
            BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
            {
                IncludeLabel = true,
                Alignment = AlignmentPositions.CENTER,
                Width = 180,
                Height = 80,
                RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                BackColor = Color.White,
                ForeColor = Color.Black,
            };

            System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, Code);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                pictureBox1.Image = img;
            }
        }
        //分拣批次码创建
        private void CreatePFTBatchImage(string BatchNo, string AppOrderNo, int Position)
        {

            this.label_apporderno.Text = AppOrderNo;
            this.label_position.Text = Position.ToString();
            BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
            {
                IncludeLabel = true,
                Alignment = AlignmentPositions.CENTER,
                Width = 180,
                Height = 60,
                RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                BackColor = Color.White,
                ForeColor = Color.Black,
            };

            System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, BatchNo);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                pictureBox_Batchno.Image = img;
            }
        }
        //下架批次码创建
        private void CreateOffImage(string GoodsCode, string GoodsName, string LocationCode, string RoadWay, string Area, string Tier, string Columns)
        {

            this.label_LocationCode.Text = LocationCode;
            this.label_OffGoodsName.Text = GoodsName;
            this.label_roadway.Text = RoadWay.ToString();
            this.label_PFTPosition.Text = Area + "-" + Tier + "-" + Columns;
            BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
            {
                IncludeLabel = true,
                Alignment = AlignmentPositions.CENTER,
                Width = 180,
                Height = 60,
                RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                BackColor = Color.White,
                ForeColor = Color.Black,
            };

            System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, GoodsCode);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                pictureBox_GoodsCode.Image = img;
            }
        }
        //创建净菜打印图片
        private void CreateProduceImage(string Code, string name, string batching, string producedate,string FreshEndDate, string weight, string storage, string cookone, string cooktwo, string cookthree, string ProduceBatchNO)
        {
            try
            {
                if (!string.IsNullOrEmpty(name))
                {
                    this.label_GoodsName.Text = name;
                    this.label_Batching.Text = batching;
                    this.label_ProductionDate.Text = producedate;
                    this.label_FreshDate.Text = FreshEndDate;
                    this.label_Weight.Text = weight + "g";
                    this.label_Storage.Text = storage;
                    this.label_CookingOne.Text = string.IsNullOrEmpty(cookone) ? "" : "1." + cookone;
                    this.label_CookingTwo.Text = string.IsNullOrEmpty(cooktwo) ? "" : "2." + cooktwo;
                    this.label_CookingThree.Text = string.IsNullOrEmpty(cookthree) ? "" : "3." + cookthree;
                    this.labelAppBatch.Text = ProduceBatchNO;
                }
                BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
                {
                    IncludeLabel = true,
                    Alignment = AlignmentPositions.CENTER,
                    Width = 180,
                    Height = 55,
                    RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                    BackColor = Color.White,
                    ForeColor = Color.Black,
                };

                System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, Code);
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    picture_BoxWOCGoodsCode .Image = img;
                }
            }
            catch { }
        }
        //创建净菜打印总数图片
        private void CreateCountImage(string GoodsName, string QTY, string ProduceBatch)
        {
            try
            {
                if (!string.IsNullOrEmpty(ProduceBatch))
                {
                    this.label_GoodsNameQTY.Text = GoodsName;
                    this.label_ProduceQty.Text = QTY;
                    BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
                    {
                        IncludeLabel = true,
                        Alignment = AlignmentPositions.CENTER,
                        Width = 167,
                        Height = 89,
                        RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                        BackColor = Color.White,
                        ForeColor = Color.Black,
                    };

                    System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, ProduceBatch);
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        pictureBox_ProduceBatch.Image = img;
                    }
                }
                else
                {
                    this.label_GoodsNameQTY.Text = GoodsName;
                    this.label_ProduceQty.Text = QTY;
                    pictureBox_ProduceBatch.Image = null;
                }
            }
            catch
            {
            }
        }
        //摘果批次条码打印
        private void CreateBatchImage(string BatchNo, string goodsName, int qty)
        {

            BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
            {
                IncludeLabel = true,
                Alignment = AlignmentPositions.CENTER,
                Width = 200,
                Height = 60,
                RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                BackColor = Color.White,
                ForeColor = Color.Black,
            };

            System.Drawing.Image img = barcode.Encode(TYPE.CODE128B, BatchNo);
            this.lblGoodsName.Text = goodsName;
            this.lblQty.Text = qty.ToString();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                pictureBox3_BatchNO.Image = img;
            }
        }
        #endregion

        #region 摘果下架指令
        //摘果下架打印
        private void button_OffPrint_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime rationdate = dateTimePicker_OffRationdate.Value.Date;
                int Batchno = 1;
                int.TryParse(textBox_OffBatch.Text, out Batchno);
                pageBatchnow = 0; //打印页数
                Offlist = new BGoods().GetOffShelvesPrintInfo(rationdate, Batchno);
                if (Offlist == null || Offlist.Count <= 0)
                {
                    DisplayRichTextBox("无指令下架数据数据");
                }
                else
                {
                    paperBatchcount = Offlist.Count;// 打印总页数
                    this.printDocumentForOffShelves.Print();
                }
            }
            catch (Exception ex)
            {

            }
        }
        //摘果下架测试打印
        private void button_OffTest_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            Offlist.Add(new PrintOffShelvesModel() { GOODSCODE = "WOC000005172", GOODSNAME = "沈大成虾仁鲜肉小馄饨120g", LOCATIONCODE = "LK4B27", ROADWAY = "1", AREA = "左", TIER = "2", COLUMNS = "3" });
            PrintPreview.Document = printDocumentForOffShelves;
            this.printDocumentForOffShelves.Print();
        }
        //摘果下架打印预览
        private void button_OffPreview_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            Offlist.Add(new PrintOffShelvesModel() { GOODSCODE = "WOC000005172", GOODSNAME = "沈大成虾仁鲜肉小馄饨120g", LOCATIONCODE = "LK4B27", ROADWAY = "1", AREA = "左", TIER = "2", COLUMNS = "3" });
            PrintPreview.Document = printDocumentForOffShelves;
            PrintPreview.ShowDialog();
        }
        #endregion

        #region 摘果批次打印
        //摘果批次打印预览
        private void button_BatchPreview_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            Batchlist.Add(new PrintBatchModel() { BATCHNO = "201705260001", APPORDERNO = "1-9", ORDERNO = "A0170521143044211", POSITION = 8 });
            pagenow = 0; //打印页数s
            papercount = 1;
            PrintPreview.Document = printDocumentForPftBatch;
            PrintPreview.ShowDialog();
        }
        //摘果批次测试打印
        private void button_test_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            Batchlist.Add(new PrintBatchModel() { BATCHNO = "201705260001", APPORDERNO = "1-9", ORDERNO = "A0170521143044211", POSITION = 8 });
            pagenow = 0; //打印页数s
            papercount = 1;
            PrintPreview.Document = printDocumentForPftBatch;
            this.printDocumentForPftBatch.Print();
        }
        //摘果批次打印
        private void button_batchPrint_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime rationdate = dateTimePicker_RationDate.Value.Date;
                int Batchno = 1;
                int.TryParse(textBox_BatchNum.Text, out Batchno);
                pageBatchnow = 0; //打印页数
                Batchlist = new BGoods().GetPftPrintBatchInfo(rationdate, Batchno);
                if (Batchlist == null || Batchlist.Count <= 0)
                {
                    DisplayRichTextBox("无分拣批次数据");
                }
                else
                {
                    paperBatchcount = Batchlist.Count;// 打印总页数
                    this.printDocumentForPftBatch.Print();
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        #region 补货标签打印
        //补货标签单条打印
        private void button_SinglePrint_Click(object sender, EventArgs e)
        {
            int Count = 0;
            papercount = 1;
            if (!int.TryParse(textBox_GoodsCount.Text.Trim(), out Count))
            {
                DisplayRichTextBox("请填写正确数量");
            }
            string goodsCode = this.textBox_GoodsCode.Text.Trim();
            if (string.IsNullOrEmpty(goodsCode))
            { DisplayRichTextBox("请填写商品编码"); }
            else
            {
                GoodsInfo info = new BGoods().GetGoodsInfoByBarCode(goodsCode);
                if (info != null)
                {
                    list.Add(new GoodsInfo { GOODSCODE = goodsCode, ROADWAY = "56", INVQTY = 23, GOODSNAME = "厨大哥竹笋老鸭煲汤料80g",AREA="中间",TIER=12,COLUMNS=21,LOCATIONCODE="mujia" });
                    papercount = 1;
                    printDialog1.Document = printDocumentForOutStock;
                    this.printDocumentForOutStock.Print();

                }
                else
                { DisplayRichTextBox("暂无该商品信息"); }
            }
        }
        //补货条码打印
        private void button_Print_Click(object sender, EventArgs e)
        {
            DisplayRichTextBox("摘果仓补货计时器开始监控......");

            outStockScanTimer = new System.Timers.Timer(int.Parse(outStockScanTime));//定时周期十分钟
            outStockScanTimer.Elapsed += outStockScanTimer_Elapsed;//到十分钟做的事件
            outStockScanTimer.AutoReset = true; //是否不断重复定时器操作
            outStockScanTimer.Enabled = true; //定时器开始用
        }
        void outStockScanTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                pagenow = 0; //打印页数
                list = new BGoods().GetOutWarningGoodsInfo();
                if (list == null || list.Count <= 0)
                {
                    //DisplayRichTextBox("无补货数据");
                }
                else
                {
                    papercount = list.Count;// 打印总页数
                    DisplayRichTextBox("打印条数：" + papercount);
                    PrintDoc(PrintElecLabel);
                }
            }
            catch (Exception ex)
            {

            }

        }
        //补货计时器关闭
        private void button_StopScanOutStock_Click(object sender, EventArgs e)
        {
            outStockScanTimer.Close(); //释放Timer占用的资源
            outStockScanTimer.Dispose();
            DisplayRichTextBox("补货计时器结束监控");
        }
        //补货条码打印预览
        private void button_PrintPreview_Click(object sender, EventArgs e)
        {
            int Count = 0;
            int.TryParse(textBox_GoodsCount.Text.Trim(), out Count);
            string goodsCode = this.textBox_GoodsCode.Text.Trim();
            if (string.IsNullOrEmpty(goodsCode))
            { goodsCode = "WOC000004468"; }
            list.Add(new GoodsInfo { GOODSCODE = goodsCode, ROADWAY = "1", INVQTY = 1, GOODSNAME = "厨大哥竹笋老鸭煲汤料80g" });
            pagenow = 0; //打印页数s
            papercount = 1;
            PrintPreview.Document = printDocumentForOutStock;
            PrintPreview.ShowDialog();
        }
        #endregion

        #region 二楼批次条码打印
        //打印
        private void btnDY_Click(object sender, EventArgs e)
        {
            try
            {
                string bcNo = this.txtBatchNo.Text.Trim();
                if (string.IsNullOrEmpty(bcNo))
                {
                    DisplayRichTextBox("请填写导入批次号");
                }
                else
                {
                    pageBatchnow = 0; //打印页数
                    listBatchNo = new ProduceGoods().getProduceBatchNO(bcNo);
                    if ((listBatchNo == null) || (listBatchNo.Count <= 0))
                    {
                        DisplayRichTextBox("无分拣批次数据");
                    }
                    else
                    {
                        paperBatchcount = listBatchNo.Count;// 打印总页数
                        this.printDocumentForBatch.Print();
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayRichTextBox("分拣批次数据打印异常:" + ex.Message);
            }
        }
        //预览
        private void btnyl_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            listBatchNo.Add(new MachingDetailModel() { PRODUCEBATCH = "170614144936802", GOODSNAME = "海派鱼香肉丝", QTY = 15 });
            pagenow = 0; //打印页数s
            papercount = 1;
            PrintPreview.Document = printDocumentForBatch;
            PrintPreview.ShowDialog();
        }
        //测试打印 
        private void button7_Click(object sender, EventArgs e)
        {
            pageBatchnow = 0; paperBatchcount = 1;
            listBatchNo.Add(new MachingDetailModel() { PRODUCEBATCH = "170614144936802", GOODSNAME = "海派鱼香肉丝", QTY = 15 });
            pagenow = 0; //打印页数s
            papercount = 1;
            PrintPreview.Document = printDocumentForBatch;
            this.printDocumentForBatch.Print();
        }
        #endregion

        #region 二楼商品配方打印
        //净菜条码单条打印
        private void button_WOCPrint_Click(object sender, EventArgs e)
        {
            try
            {
                button_Print.Enabled = false;
                string single_manufactureDate = DateCheckbox.Checked == true ? single_manufactureDate = DateTime.Now.AddDays(1).ToShortDateString() : single_manufactureDate = DateTime.Now.ToShortDateString();
                string batchnumber = this.textBox_BatchNumber.Text.Trim();
                if (string.IsNullOrEmpty(batchnumber))
                {
                    DisplayRichTextBox("请输入导入批次号");
                    return;
                }
                listForPrint = new ProduceGoods().getAllMachingDetailByBatchNumber(batchnumber);
                if (listForPrint == null || listForPrint.Count <= 0)
                {
                    DisplayRichTextBox("无净菜详细数据");
                    return;
                }
                else
                {
                    #region 数据处理
                    listM.Clear();
                    MachingDetailModel infotmp = listForPrint[0];
                    GoodsidForDetail = infotmp.GOODSID;//第一个商品ID
                    int papercountForDetail = 0;
                    infotmp.SEQ = -2;//打印总数量条码
                    listM.Add(GetNewObject(infotmp));
                    foreach (MachingDetailModel info in listForPrint)
                    {
                        if ((info.GOODSID != GoodsidForDetail && info.ALLQTY > 20 && !string.IsNullOrEmpty(info.BATCHING)) || (info.GOODSID != GoodsidForDetail && string.IsNullOrEmpty(info.BATCHING)))
                        {
                            info.SEQ = -2;//打印总数量条码
                            listM.Add(GetNewObject(info));
                        }
                        if (info.GOODSID != GoodsidForDetail)
                        {
                            papercountForDetail = 0;
                            GoodsidForDetail = info.GOODSID;
                        }
                        if (!string.IsNullOrEmpty(info.BATCHING))
                        {
                            info.SEQ = -1;//打印批次数量总条码
                            listM.Add(GetNewObject(info));
                            for (int i = 0; i < info.QTY; i++)
                            {
                                papercountForDetail++;
                                info.SEQ = papercountForDetail;//打印正常条码
                                listM.Add(GetNewObject(info));
                            }
                        }
                    }
                    #endregion
                    pagenow = 0;
                    papercount = listM.Count;
                    this.printDialog1.Document = printDocumentForDetail;
                    this.printDocumentForDetail.Print();
                }
            }
            catch (Exception ex)
            {
                DisplayRichTextBox("净菜详细数据打印异常:" + ex.Message);
            }
            finally
            { button_Print.Enabled = true; }
        }
        //净菜条码单条打印预览
        private void button_WOCPrintPreview_Click(object sender, EventArgs e)
        {
            string goodsCode = this.textBoxProduceGoodsCode.Text.Trim();
            if (string.IsNullOrEmpty(goodsCode))
            {
                goodsCode = "WOC000405";
            }
            MachingDetailModel model = new ProduceGoods().getAllMachingDetailByGoodsCode(goodsCode);
            if (model == null)
            {
                listM.Insert(0, new MachingDetailModel { GOODSCODE = goodsCode });
            }
            else
            {
                listM.Insert(0, model);
                CreateProduceImage(model.GOODSCODE, model.GOODSNAME, model.BATCHING, "2017-02-02","2017-02-04", model.WEIGHT, model.STORAGE, model.COOKINGONE, model.COOKINGTWO, model.COOKINGTHREE, "2-2-2");
            }
            pagenow = 0; //打印页数s
            
            papercount = 1;
            PrintPreview.Document = printDocumentForWOC;
            PrintPreview.ShowDialog();
        }
        //净菜单条打印
        private void button_WOCSinglePrint_Click(object sender, EventArgs e)
        {
            string goodsCode = this.textBoxProduceGoodsCode.Text.Trim();
            string single_manufactureDate = DateCheckbox.Checked == true ? single_manufactureDate = DateTime.Now.AddDays(1).ToShortDateString() : single_manufactureDate = DateTime.Now.ToShortDateString();
            string single_FreshEndDate = DateCheckbox.Checked == true ? single_FreshEndDate = DateTime.Now.AddDays(3).ToShortDateString() : single_FreshEndDate = DateTime.Now.AddDays(2).ToShortDateString();
            if (string.IsNullOrEmpty(goodsCode))
            {
                DisplayRichTextBox("请填写商品编码");
            }
            else
            {
                MachingDetailModel model = new ProduceGoods().getAllMachingDetailByGoodsCode(goodsCode);
                if (model == null)
                {
                    listM.Insert(0, new MachingDetailModel { GOODSCODE = goodsCode });
                    return;
                }
                else
                {
                    listM.Insert(0, model);
                }
                papercount = int.Parse(numericUpDown_PrintCount.Value.ToString());
                pagenow = 0;
                var info = listM[pagenow];
                DisplayRichTextBox(info.GOODSCODE + info.GOODSNAME);
                CreateProduceImage(info.GOODSCODE, info.GOODSNAME, info.BATCHING, single_manufactureDate, single_FreshEndDate, info.WEIGHT, info.STORAGE, info.COOKINGONE, info.COOKINGTWO, info.COOKINGTHREE, "");
                listM.Clear();
                printDialog1.Document = printDocumentForWOC;
                this.printDocumentForWOC.Print();
            }
        }

        //扫描加工批次号输入事件
        private void textBox_ProduceBatchNO_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)//扫码枪扫描
            {
                string Batchno_manufactureDate = DateCheckbox.Checked == true ? Batchno_manufactureDate = DateTime.Now.AddDays(1).ToShortDateString() : Batchno_manufactureDate = DateTime.Now.ToShortDateString();
                string single_FreshEndDate = DateCheckbox.Checked == true ? single_FreshEndDate = DateTime.Now.AddDays(3).ToShortDateString() : single_FreshEndDate = DateTime.Now.AddDays(2).ToShortDateString();
                string BatchNO = textBox_ProduceBatchNO.Text.Trim();
                if (!string.IsNullOrEmpty(BatchNO))
                {
                    MachingDetailModel model = new ProduceGoods().getAllMachingDetailByProduceBatchNO(BatchNO);
                    if (model == null)
                    {
                        DisplayRichTextBox("无批次" + BatchNO + " 的相关商品信息");
                        return;
                    }
                    else
                    {
                        listM.Insert(0, model);
                    }
                    papercount = model.QTY;
                    pagenow = 0;
                    DisplayRichTextBox(model.GOODSCODE + model.GOODSNAME);
                    CreateProduceImage(model.GOODSCODE, model.GOODSNAME, model.BATCHING, Batchno_manufactureDate, single_FreshEndDate, model.WEIGHT, model.STORAGE, model.COOKINGONE, model.COOKINGTWO, model.COOKINGTHREE, "2-2-2");
                    printDialog1.Document = printDocumentForWOC;
                    this.printDocumentForWOC.Print();
                }
                else
                {
                    DisplayRichTextBox("请重新扫描，并确保光标处于加工批次号文本框内");
                }
                textBox_ProduceBatchNO.Text = "";
                textBox_ProduceBatchNO.Focus();
            }
        }
        #endregion

        
    }
}
